var appVersion = 20170802;

function ajax_post_json_request(method, data, success_function_handle, error_function_handle) {
    mui.ajax('/api/v1/' + method, {
        data: mui.extend(data, {version: "1.0", t: new Date().getTime()}),
        //dataType: 'json',//服务器返回json格式数据
        type: 'post',//HTTP请求类型
        timeout: 10000,//超时时间设置为10秒；
        async: true,
        //headers: {'Content-Type': 'application/json'},
        beforeSend: function () {
            //showLoading("loading...")
        },
        complete: function () {
            //hideLoading();
        },
        success: function (data) {
            if (777 === data.code || (404 === data.code && getUserId())) {
                var host = window.location.host;
                if (-1 === host.indexOf("localhost") && -1 === host.indexOf("127.0.0.1")) {
                    window.location.href = "http://" + host + "/wechat?url=" + window.location.href;
                }
            } else success_function_handle(data);
        },
        error: function (xhr, type, errorThrown) {
            if (error_function_handle) {
                error_function_handle(type);
            } else {
                mui.alert("本地请求失败，请检查网络环境是否正常！" + type + errorThrown);
                //异常处理；
                console.log(type);
            }
        }
    });
}

function appReady(readyHandleFunc) {
    if (mui.os.plus) {
        mui.plusReady(function () {
            setTimeout(function () {
                if (readyHandleFunc) readyHandleFunc();
            }, 1000);
        });
    } else {
        mui.ready(function () {
            if (readyHandleFunc) readyHandleFunc();
        });
    }
}

/*
*  获取头部地址
* */
function getUrlParam(key) {
    var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
    var result = window.location.search.substr(1).match(reg);
    return result ? decodeURIComponent(result[2]) : "";
}

jQuery(function () {
    var appStoreVersion = localStorage.getItem("appVersion");
    if (!appStoreVersion) appStoreVersion = 0;
    if (appVersion > appStoreVersion) {
        localStorage.clear();
        localStorage.setItem("appVersion", appVersion);
    }

    var openId = getUrlParam("openId");
    var userId = getUrlParam("userId");
    if (!openId.isEmpty()) localStorage.setItem("openId", openId);
    if (!userId.isEmpty()) localStorage.setItem("userId", userId);

    var storageUserId = localStorage.getItem("userId");
    var isInWeChat = window.navigator.userAgent.toLowerCase().indexOf("micromessenger");
    if (isInWeChat && (null === storageUserId || storageUserId.isEmpty() || 'null' === storageUserId)) {
        var host = window.location.host;
        if (host.indexOf("localhost") === -1 && host.indexOf("127.0.0.1") === -1) {
            window.location.href = "http://" + host + "/wechat?url=" + window.location.href.split('#')[0];
        }
    }
});

function getUserId() {
    var userId = localStorage.getItem("userId");
    if (null != userId && !userId.isEmpty()) return userId;
}

function getKey() {
    var key = localStorage.getItem("key");
    if (null != key && !key.isEmpty()) return key;
}

/**
 * 将时间戳转换成指定格式的时间
 * @param timstamp
 * @param format "yyyy/MM/dd HH:mm:ss"
 * @returns {*}
 */
function timestampToFormatString(timstamp, format) {
    var newDate = new Date();
    newDate.setTime(timstamp * 1000);
    return newDate.format(format)
}

String.prototype.isEmpty = function () {
    return this.trim().length == 0;
};
String.prototype.isNotEmpty = function () {
    return !this.isEmpty();
};
String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, "");
};
String.prototype.equals = function (target) {
    return this.trim() == target;
};
String.prototype.notEquals = function (target) {
    return this.trim() != target;
};
String.prototype.isDecimal = function () {
    var doubleExp = new RegExp("^\\d+(\\.\\d+)?$");
    return doubleExp.test(this.trim());
};
String.prototype.isInteger = function () {
    var integerExp = new RegExp("^((-|\\+)?[1-9]\\d*)|0$");
    return integerExp.test(this.trim());
};
String.prototype.isEmail = function () {
    var integerExp = /^([\w{1,}])([\w-]*(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,3}(?:\.[a-z]{2})?)$/i;
    return integerExp.test(this.trim());
};
String.prototype.isUrl = function () {
    if (this.isEmpty()) return false;
    var reg = /(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
    return reg.test(this);
};
String.prototype.gblen = function () {//测试每个字符的长度 汉字=2个字符 英文=1个字符
    var len = 0;
    for (var i = 0; i < this.length; i++) {
        if (this.charCodeAt(i) > 127 || this.charCodeAt(i) == 94) {
            len += 2;
        } else {
            len++;
        }
    }
    return len;
}
String.format = function () {
    if (arguments.length == 0)
        return null;
    var str = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
};
Date.prototype.format = function (format) {
    var date = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S+": this.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
};
Object.isNullOrUndefined = function (obj) {
    if (typeof (obj) == "undefined" || obj == null
        || obj.toString().length == 0) {
        return true;
    } else {
        return false;
    }
};

//展示整数变小数
function showDecimal(num) {
    num = parseInt(num);
    return (num / 100).toFixed(2);
}

//表单提交--小数*100--变整数
function toInteger(num) {
    num = parseFloat(num);
    return parseInt((num.toFixed(2)) * 100);
}

//將當前時間轉換成时间戳
function timeStringToStamp(timeString) {
    var timeStamp = Date.parse(new Date(timeString));
    timeStamp = timeStamp / 1000;
    return timeStamp;
}

//将格式化后的时间转化成毫秒数
function timeToMillisecond(timeString) {
    var millisecond = new Date(timeString).getTime() / 1000;
    return millisecond;
}

//根据省份名称查找对应ID
function provinceToId(province) {
    for (var i = 0, len = provinceData.length; i < len; i++) {
        if (province == provinceData[i].text) {
            return provinceData[i].value;
        }
    }
}

//根据省份名称查找对应ID
function provinceToCenter(province) {
    for (var i = 0, len = cityData.length; i < len; i++) {
        if (province === cityData[i].text) {
            console.log(cityData[i].children);
            return cityData[i].text + cityData[i].children[0].text;
        }
    }
}

//根据城市名称查找对应ID
function cityToId(province, city) {
    for (var i = 0, len = cityData.length; i < len; i++) {
        if (province == cityData[i].text) {
            for (var j = 0, len1 = cityData[i].children.length; j < len1; j++) {
                if (city == cityData[i].children[j].text) {
                    return cityData[i].children[j].value;
                }
            }
        }
    }
}

function availableTime(date) {
    var currentTime = (new Date(date * 1000).toLocaleString()
        .substr(0, 9)).replace(/[\u4e00-\u9fa5]{2}/, '')
        .replace(new RegExp('/', 'g'), '.') + ' ';
    return currentTime;
}

var showMaskCallbackReturn = false;
var mask = mui.createMask(function () {
    return showMaskCallbackReturn;
});

function showLoading(text, showMask) {
    var html = '<div id="maskLoading" style="position: fixed;z-index: 999;top: 50%;left: 50%;margin-left: -50px;margin-top: -50px;height: 100px;width: 100px;background-color: rgba(54, 54, 54, 0.84);border-radius: 10px;text-align: center;"><i class="mui-spinner" style="height: 50px;width: 50px;margin-top: 14px;"></i><p>' + text + '</p></div>';
    if (showMask) {
        showMaskCallbackReturn = false;
        mask.show();
    }//显示遮罩
    jQuery('body').append(html);
}

function hideLoading() {
    showMaskCallbackReturn = true;
    mask.close();//关闭遮罩
    jQuery("body #maskLoading").remove();
}

//异步加载javascript文件
function loadScript(src) {
    //创建script标签
    var script = document.createElement("script");
    //设置标签的type属性
    script.type = "text/javascript";
    //设置标签的链接地址
    script.src = src;
    //添加标签到dom
    document.body.appendChild(script);
}

//将阿拉伯数字转换成中文数字
function formatToDay(day) {
    var dayTime;
    switch (day) {
        case 1:
            dayTime = '一'
            break;
        case 2:
            dayTime = '二'
            break;
        case 3:
            dayTime = '三'
            break;
        case 4:
            dayTime = '四'
            break;
        case 5:
            dayTime = '五'
            break;
        case 6:
            dayTime = '六'
            break;
        case 7:
            dayTime = '日'
            break;
    }
    return dayTime;
}

//aes加密
loadScript("http://react.file.alimmdn.com/aes.js");